﻿using Authentication.Model.Interface;
using Authentication.Model.Model;
using Common.Contract.Paging;
using Common.Contract.SystemConfig.Record;
using Common.Contract.SystemConfig.Request;
using Common.Contract.SystemConfig.Response;
using Common.Service.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Util;
using System.Threading.Tasks;

namespace Authentication.Core.ServiceCommand
{
    public class SearchAppErrorServiceCommand : ProviderServiceCommand<IProviderFactory, SearchApplicationErrorRequest, SearchApplicationErrorResponse>
    {
        public SearchAppErrorServiceCommand(IProviderFactory providers) : base(providers) { }

        protected override void Validate(SearchApplicationErrorRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
        }

        protected override bool OnExecute(SearchApplicationErrorResponse response)
        {
            bool isSuccess = true;
            string errorMessage = string.Empty;
            int pageSize = 0, pageIndex = 0, totalRecord = 0;
            List<ApplicationErrorRecord> records = null;
            var applicationKey = Request.Header.ApplicationKey;
            if (Request.Page != null)
            {
                pageIndex = Request.Page.PageIndex ?? 0;
                pageSize = Request.Page.PageSize ?? 0;
            }
            List<ApplicationError> applications = Providers.Configurations.SearchAppError(out totalRecord, Request.TransferFlag, pageSize, pageIndex);
            if (applications != null)
            {
                records = applications.Select(x => new ApplicationErrorRecord
                {
                    CreationDate = x.CreateTime,
                    Line = x.Line,
                    Message = x.Msg,
                    Name = x.Name,
                    TransferFlag = x.SoTransferFlag.ToBoolean(),
                }).ToList();
            }

            response.Records = records;
            response.Page = new PageRecord
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                TotalRecords = totalRecord
            };
            return isSuccess;
        }
    }
}
